
/**
 * @param element {Element} 
 * @param vars {Object} map from variable names to the corresponding part of the query
 * @param query {Object} the query
 */
function collectQuery(element, vars) {
  var jsfor = element.getAttribute("jsfor");
  if (jsfor) {
    processJsfor(jsfor, vars);
  } 

  var jscontent = element.getAttribute("jscontent");
  if (jscontent) {
    processJscontent(jscontent, vars);
  }

  // recurse
  var children = element.childNodes;
  for(var i = 0; i < children.length; i++) {
    var child = children[i];
    if (child.nodeType == DOM_ELEMENT_NODE) {
      vars = jQuery.extend({}, vars);
      collectQuery(child, vars);
    }
  }
}


function processJsfor(jsfor, vars) {
  var cut = jsfor.indexOf(':');
  var varName = jsfor.substring(0, cut);
  var expression = jsfor.substring(cut + 1);
  
//  console.log("jsfor vars before: " + JSON.stringify(vars));
//  console.log("varName: " + varName + "; vars[expression]:" + JSON.stringify(vars[expression]));
//  if(vars[expression] == null || !vars[expression].length) {
//    vars[expression] = [{}];
//  }
  vars[varName] = vars[expression][0];
  
  console.log("jsfor vars: " + JSON.stringify(vars));
  
}

function processJscontent(expr, vars) {
  var path = expr.split(".");
  var context;

  //console.log("Variable: "+ path[0]);
  if (path.length == 1) {
    // returning existing variable value, no need to update query.
    return;
  }
  console.log("Variable: " + path[0]);
  var context = vars[path[0]];

  // TODO: loop.

  // If the context is an array (jsfor, jsselect), resolve to the first element
  if (context.length) {
    console.log("Error: context must not be an array!")
    context = context[0];
  }
  var propertyName = path[1];
  //console.log("Property name: " + propertyName)
  if (!context[propertyName]) {
    context[propertyName] = null; 
  }
  

  console.log("jscontent vars: " + JSON.stringify(vars))
  
}

